<template>
    <div>
       <!-- 表单组件，绑定了表单实例引用、表单数据模型、尺寸等属性 -->
       <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="订单主题" prop="orderSubject">
            <el-input v-model="ruleForm.orderSubject" />
            </el-form-item>
            <el-form-item>
                 <!-- 到票单号表单字段 -->
            <el-form-item label="采购单号" prop="arrivalNumber">
                <!-- 输入框，双向绑定 ruleForm 的 arrivalNumber 字段，设置了只读、可清除等属性，并绑定点击事件 -->
                <el-input v-model="ruleForm.purchaseOrderNumber" autocomplete="off" style="width: 180px; height: 30px"
                    :readonly="ruleForm.autoGenerate" clearable @click.native="handleCodeClick" />
                <!-- 输入框前置内容插槽，显示字母 'R' -->
                <template #prepend>R</template>
                <!-- 开关组件，双向绑定 ruleForm 的 autoGenerate 字段，设置激活文本和颜色，并绑定切换事件 -->
                <el-switch width="40" v-model="ruleForm.autoGenerate" active-text="自动生成" active-color="#67C23A"
                    @change="handleSwitchChange" />
            </el-form-item>
            <!-- 到票主题表单字段 -->
            <el-form-item label="关联请购" prop="relatedPurchaseRequisition">
                <!-- 输入框，双向绑定 ruleForm 的 arrivalName 字段 -->
                <el-input v-model="ruleForm.relatedPurchaseRequisition" />
            </el-form-item>
            </el-form-item>
           
           
            <el-form-item label="关联销售订单">
                <!-- 复选框，双向绑定 isUnbindSalesOrder 字段，并绑定切换事件，用于控制销售订单表格的显示隐藏 -->
                <el-checkbox v-model="isUnbindSalesOrder" @change="toggleSalesOrderTable">{{ isUnbindSalesOrder ?
                    '绑定销售订单' : '不绑定销售订单' }}</el-checkbox>
            </el-form-item>
        </el-form>
        

        <el-form-item label="采购日期">
      <el-date-picker
        v-model="ruleForm.purchaseDate"
        type="date"
        placeholder="Pick a date"
        clearable
      />
    </el-form-item>

<el-form>
    <el-row>
      <el-col :span="12">
        <el-form-item label="供应商名称">
      <el-select
        v-model="ruleForm.supplierName"
        placeholder="供应商名称"
        clearable
      >
        <el-option label="天马行空项目" value="天马行空项目" />
        <el-option label="不靠谱项目" value="不靠谱项目" />
        <el-option label="吴佳乐回家项目" value="吴佳乐回家项目" />
        <el-option label="爱吃兔项目" value="爱吃兔项目" />
      </el-select>
    </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="ruleForm.contactPerson" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="ruleForm.contactPhone" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="采购人员" prop="purchaser">
          <el-input v-model="ruleForm.purchaser" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="采购部门" prop="purchaseDepartment">
          <el-input v-model="ruleForm.purchaseDepartment" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系方式" prop="contactWay">
          <el-input v-model="ruleForm.contactWay" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">


        <el-form-item label="关联项目">
      <el-select
        v-model="ruleForm.relatedProject"
        placeholder="关联项目"
        clearable
      >
        <el-option label="天马行空项目" value="天马行空项目" />
        <el-option label="不靠谱项目" value="不靠谱项目" />
        <el-option label="吴佳乐回家项目" value="吴佳乐回家项目" />
        <el-option label="爱吃兔项目" value="爱吃兔项目" />
      </el-select>
    </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="结算方式" prop="settlementMethod">
          <el-input v-model="ruleForm.settlementMethod" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="交付地址" prop="deliveryAddress">
          <el-input v-model="ruleForm.deliveryAddress" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="ruleForm.remarks" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

        <!-- 根据 isUnbindSalesOrder 的值决定是否显示销售订单表格区域 -->
        <div v-if="salesOrderTableVisible">
            <!-- 添加按钮，点击时调用 addSalesOrderRow 方法添加销售订单行 -->
            <!-- <el-button @click="addSalesOrderRow">添加</el-button> -->
            <!-- 销售订单表格组件，绑定表格数据和样式 -->
            <el-table @selection-change="handleSelection" :data="tableData" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <!-- 销售订单表格列，显示销售单号 -->
                <el-table-column prop="serialNumber" label="销售单号" />
                <!-- 销售订单表格列，显示销售订单主题 -->
                <el-table-column prop="itemNumber" label="销售订单主题" />
                <!-- 销售订单表格列，显示客户名称 -->
                <el-table-column prop="itemName" label="客户名称" />
                <!-- 销售订单表格列，显示销售日期 -->
                <el-table-column prop="specificationModel" label="销售日期" />
                <!-- 销售订单表格列，显示总金额 -->
                <el-table-column prop="unit" label="总金额" />
                <!-- 销售订单表格列，显示已开票金额 -->
                <el-table-column prop="brand" label="已开票金额" />
                <!-- 销售订单表格列，显示开票金额 -->
                <el-table-column prop="purchaseQuantity" label="开票金额">
                    <template #default="scope">
                        <el-input v-model="scope.row.purchaseQuantity" />
                    </template>
                </el-table-column>
                <!-- 销售订单表格列，显示备注 -->
                <el-table-column prop="mainUnitQuantity" label="备注">
                    <template #default="scope">
                        <el-input v-model="scope.row.mainUnitQuantity" type="textarea" />
                    </template>
                </el-table-column>
                <!-- 销售订单表格列，显示操作按钮 -->
                <el-table-column label="操作">
                    <template #default="scope">
                        <!-- 移除按钮，点击时调用 removeSalesOrderRow 方法移除对应行数据 -->
                        <el-button size="small" @click="removeSalesOrderRow(scope.$index)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 表单底部操作区域 -->
        <div class="dialog-footer">
            <!-- 清空按钮，点击时调用 resetForm 方法重置表单 -->
            <el-button @click="resetForm(ruleFormRef)">清空</el-button>
            <!-- 确定按钮，点击时调用 AddForm 方法提交表单数据 -->
            <el-button type="primary" @click="AddForm(ruleFormRef)">
                确定
            </el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
// 导入路由模块
import router from '@/router';
// 导入 axios 用于发送 HTTP 请求
import axios from 'axios';
// 导入 Element Plus 相关组件和消息提示等功能
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination, FormInstance } from 'element-plus';
// 导入 Vue 3 的组合式 API 相关函数
import { onMounted, ref, reactive, computed } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;

// 定义响应式变量存储销售订单表格数据，初始为空数组
const tableData = ref<{ WJId: number }[]>([]);
// 定义响应式变量存储是否不绑定销售订单的状态，初始为 false
const isUnbindSalesOrder = ref(false);
// 计算属性，根据 isUnbindSalesOrder 的值决定销售订单表格是否可见
const salesOrderTableVisible = computed(() => !isUnbindSalesOrder.value);

// 定义函数从后端接口获取销售订单数据
const fetchData = () => {
    axios.get(apiUrl+'/T5/Setting/ShowCG')
        .then((res) => {
            // 将获取到的数据赋值给 tableData
            tableData.value = res.data.data;
        })
        .catch((error) => {
            console.error('获取销售订单数据失败:', error);
        });
};
// 定义函数移除销售订单表格中指定索引的行
const removeSalesOrderRow = (index: number) => {
    tableData.value.splice(index, 1);
};

// 定义响应式变量存储表单尺寸，初始为 'default'
const formSize = ref('default');
// 定义响应式变量存储表单实例引用
const ruleFormRef = ref<FormInstance>();
// 定义响应式对象存储表单数据模型
const ruleForm = reactive({
    purchaseOrderId: 0,
  orderSubject: "",
  purchaseOrderNumber: "",
  relatedPurchaseRequisition: "",
  relatedSalesOrder: "",
  purchaseDate: "2025-04-17T01:52:30.004Z",
  supplierName: "",
  contactPerson: "",
  contactPhone: "",
  purchaser: "",
  purchaseDepartment: "",
  contactWay: "",
  relatedProject: "",
  settlementMethod: "",
  deliveryAddress: "",
  remarks: "",
  isDelete: false,
  WJId: [],
  autoGenerate:false
})


// 定义异步函数提交表单数据
const AddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    // 验证表单数据
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送 POST 请求提交表单数据到后端接口
            axios.post(apiUrl+'/T6/setting/Addpur', ruleForm)
                .then(res => {
                    if (res.data.code === 100) {
                        // 提交成功时显示成功消息
                        ElMessage.success(res.data.msg);
                        router.push('/ShowCG');
                    } else {
                        // 提交失败时显示错误消息
                        ElMessage.error("添加失败，请稍后重试");
                    }
                })
                .catch((error) => {
                    console.error('提交表单数据失败:', error);
                    ElMessage.error('提交表单数据时发生错误，请稍后重试');
                });
        } else {
            console.log('error submit!', fields);
            // 表单验证失败时显示错误消息
            ElMessage.error('表单验证失败，请检查输入内容');
        }
    });
};

const selectedProcessIds = ref([]);

const zhuanhuan = () => {
    ruleForm.WJId = selectedProcessIds.value;
    console.log(ruleForm.WJId, "4444");
}
// 处理表格选择变化事件
const handleSelection = (selection: any) => {
    console.log(selection, "666");
    selectedProcessIds.value = selection.map(x => x.serialNumber); // 假设工序对象有 id 属性，根据实际情况修改
    zhuanhuan();
    console.log(selectedProcessIds.value, 'selectedProcessIds:');
}

// 定义函数生成物料产品编号，使用当前时间戳生成编号
const generateCode = () => {
    const timestamp = new Date().toISOString().replace(/[-:TZ]/g, "").substring(0, 14); // 获取精确到毫秒的时间戳
    ruleForm.purchaseOrderNumber = `DP${timestamp}`;
};

// 定义函数处理开关组件的切换事件，根据开关状态生成或清空开票单号
const handleSwitchChange = (val: boolean) => {
    ruleForm.autoGenerate = val;
    if (val) {
        generateCode(); // 开启自动生成时立即生成
    } else {
        ruleForm.purchaseOrderNumber = ""; // 关闭时清空编号
    }
};

// 定义函数处理开票单号输入框的点击事件，当自动生成开启时重新生成编号
const handleCodeClick = () => {
    if (ruleForm.autoGenerate) {
        generateCode(); // 点击输入框时重新生成
    }
};

// 定义函数重置表单字段
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

// 生成一个包含 10000 个选项的数组，每个选项包含值和标签
const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));

// 组件挂载时调用 fetchData 函数获取销售订单数据
onMounted(() => {
    fetchData();
});
</script>
<style>
/* // 定义表单底部操作区域的样式，文本右对齐，内边距为 10px */
.dialog-footer {
    text-align: right;
    padding: 10px;
}
</style>